<?php

declare(strict_types=1);

namespace App\Exceptions;

use App\Mail\ExceptionOccured;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\ErrorHandler\ErrorHandler;
use Symfony\Component\ErrorHandler\Exception\FlattenException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @return void
     */
    public function report(Exception $exception)
    {
        if (prod()) {
            $enableEmailExceptions = config('exceptions.emailExceptionEnabled');

            if (empty($enableEmailExceptions)) {
                $enableEmailExceptions = config('exceptions.emailExceptionEnabledDefault');
            }

            if ($enableEmailExceptions && $this->shouldReport($exception)) {
                $this->sendEmail($exception);
            }
        }
        parent::report($exception);
    }

    public function sendEmail(Exception $e)
    {
        try {
            $flattenException = FlattenException::create($e);
            $errorHandler = new \Symfony\Component\Debug\ExceptionHandler();
            $html = $errorHandler->getHtml($flattenException);

            Mail::send(new ExceptionOccured($html));
        } catch (Exception $exception) {
            Log::error($exception->getMessage());
        }
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}
